package lion.web.interceptors.cluster.session;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.dev.lang.MapJ;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.RequestHandler;
import lion.framework.core.web.RequestInterceptor;

import org.apache.commons.lang.StringUtils;

/**
 * 会话拦截类，该类判断客户端会话cookie并将request转为封装过getSession的ClusteredSessionRequestWrapper
 * 
 * <pre>
 * time   2013 2013年12月19日 下午4:44:52
 * mail   hl_0074@sina.com
 * </pre>
 * 
 * @author lion
 */
public class ClusteredSessionInterceptor implements RequestInterceptor {

	private String key;
	private String domain;

	public ClusteredSessionInterceptor() {

		Config config = ConfigManager.getConfig("framework");
		MapJ m = config.getOne("framework.mvc.clustersession");
		if (m == null) { return; }
		key = m.getString("key", "JSESSIONID");
		domain = m.getString("domain");
	}

	@Override
	public void intercept(HttpServletRequest request, HttpServletResponse response, RequestHandler handler) throws Exception {

		Cookie[] cookies = request.getCookies();
		String id = null;
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key)) {
					id = cookie.getValue();
				}
			}
		}
		if (StringUtils.isBlank(id)) {
			id = UUID.randomUUID().toString().replace("-", "");
			Cookie cookie = new Cookie(key, id);
			cookie.setMaxAge(-1);// 只存于浏览器内存当中。
			cookie.setPath("/");
			if (StringUtils.isNotBlank(domain)) {
				cookie.setDomain(domain);
			}
			response.addCookie(cookie);
		}
		ClusteredSessionRequestWrapper wrapper = new ClusteredSessionRequestWrapper(id, request);
		try {
			handler.handle(wrapper, response);
		} finally {
			wrapper.synchroSession();
		}
	}
}
